//
//  SystemNoticeViewController.m
//  JimiPay
//
//  Created by yull on 16/1/7.
//  Copyright (c) 2016年 com.shengyun. All rights reserved.
//

#import "SystemNoticeViewController.h"
#import "SystemNoticeCell.h"
#import "NoticeDetailViewController.h"

#import "SVPullToRefresh.h"

@interface SystemNoticeViewController ()

@property (nonatomic, strong) NSMutableArray *notifications;
@property (nonatomic, assign) NSInteger start;
@property (nonatomic, strong) NSString *lastId;

@end

@implementation SystemNoticeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.navigationItem.title = @"系统公告";
    [self setupCustomBackItem];
    
    self.notifications = [NSMutableArray array];
    [self.tableView registerNib:[UINib nibWithNibName:@"SystemNoticeCell" bundle:nil] forCellReuseIdentifier:@"SystemNoticeCell"];
    self.tableView.tableFooterView = [[UIView alloc] init];
    
    __weak typeof(self) wself = self;
    
    [self.tableView addPullToRefreshWithActionHandler:^{
        wself.start = 0;
        wself.lastId = nil;
        [wself loadData];
    }];
    
    [self.tableView addInfiniteScrollingWithActionHandler:^{
        [wself loadData];
    }];
    
    [self loadData];
}

- (void)clearAppBadge
{
    if ([[[UIDevice currentDevice] systemVersion] compare:@"8.0" options:NSNumericSearch] != NSOrderedDescending) {
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge categories:nil];
        
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        
        UIApplication *app = [UIApplication sharedApplication];
        // 应用程序右上角数字
        app.applicationIconBadgeNumber = 0;
    } else {
        UIApplication *app = [UIApplication sharedApplication];
        
        [app registerForRemoteNotificationTypes:
         (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert |
                                    UIRemoteNotificationTypeBadge |
                                    UIRemoteNotificationTypeSound)];
        // 应用程序右上角数字
        app.applicationIconBadgeNumber = 0;
    }
    
    [[NSUserDefaults standardUserDefaults] setObject:@(0) forKey:@"IconBadgeNumber"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)loadData
{
    [TDHttpEngine requestFor_NOTICE_WithCustId:[[NSUserDefaults standardUserDefaults] objectForKey:CUST_ID]
                                    custMobile:[[NSUserDefaults standardUserDefaults] objectForKey:CUST_MOBILE]
                                         start:self.start
                                      pageSize:10
                                        lastId:self.lastId
                                      complete:^(BOOL succeed, NSString *msg, id reqBody) {
                                          [self.tableView.pullToRefreshView stopAnimating];
                                          [self.tableView.infiniteScrollingView stopAnimating];
                                          
                                          if (succeed) {
                                              
                                              [self clearAppBadge];
                                              
                                              NSArray *list = [reqBody objectForKey:@"noticeList"];
                                              
                                              if (self.start == 0) {
                                                  [self.notifications removeAllObjects];
                                              }
                                              
                                              [self.notifications addObjectsFromArray:list];
                                              
                                              if (self.start == 0 && self.notifications.count) {
                                                  NSDictionary *dic = self.notifications.firstObject;
                                                  if ([dic objectForKey:@"noticeId"]) {
                                                      [[NSUserDefaults standardUserDefaults] setObject:[dic objectForKey:@"noticeId"] forKey:@"NOTICELASTID"];
                                                      [[NSUserDefaults standardUserDefaults] synchronize];
                                                  }
                                              }
                                              
                                              [self.tableView reloadData];
                                              
                                              self.start += list.count;
                                              
                                              NSDictionary *dic = self.notifications.lastObject;
                                              if (dic) {
                                                  self.lastId = [dic objectForKey:@"noticeId"];
                                              }
                                              
                                              if (list.count < 10) {
                                                  self.tableView.showsInfiniteScrolling = NO;
                                                  if (self.notifications.count == 0) {
                                                      self.blankView.hidden = NO;
                                                  }
                                              }
                                          } else {
                                              [self.view makeToast:msg duration:2.0f position:@"Center"];
                                          }
                                      }];
}

- (void)viewDidLayoutSubviews
{
    // iOS 7
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    // iOS 8
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)loadContent:(SystemNoticeCell *)cell indexPath:(NSIndexPath *)indexPath {
    
    NSDictionary *noticeDic = [self.notifications objectAtIndex:indexPath.row];
    NSString *title = [noticeDic objectForKey:@"noticeTitle"];
    if (![title isKindOfClass:[NSString class]]) {
        title = @"--";
    }
    
    NSString *content = [noticeDic objectForKey:@"noticeBody"];
    if (![content isKindOfClass:[NSString class]]) {
        content = @"--";
    }
    
    NSString *time = [noticeDic objectForKey:@"createDate"];
    if (![time isKindOfClass:[NSString class]]) {
        time = @"--";
    } else {
        time = [NSString stringWithFormat:@"%@月%@日 %@:%@:%@",
                [time substringWithRange:NSMakeRange(4, 2)],
                [time substringWithRange:NSMakeRange(6, 2)],
                [time substringWithRange:NSMakeRange(8, 2)],
                [time substringWithRange:NSMakeRange(10, 2)],
                [time substringWithRange:NSMakeRange(12, 2)]];
    }
    
    cell.titleL.text = title;
    
//    NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[content dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
//    cell.contentL.attributedText = attrStr;
    cell.contentL.text = content;
    
    cell.timeL.text = time;
//    [contentL sizeToFit];
//    
//    CGRect frame = timeL.frame;
//    frame.origin.y = CGRectGetMaxY(contentL.frame) + 3;
//    timeL.frame = frame;
}

#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 114;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static SystemNoticeCell *cell;
    if (!cell) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"SystemNoticeCell"];
    }
    
    [self loadContent:cell indexPath:indexPath];
    
    CGSize size = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    return size.height + 1;
    
//    NSDictionary *noticeDic = [self.notifications objectAtIndex:indexPath.row];
//    NSString *content = [noticeDic objectForKey:@"noticeBody"];
//    if (![content isKindOfClass:[NSString class]]) {
//        content = @"";
//    }
//    
//    CGSize size = [content sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:CGSizeMake(self.view.frame.size.width - 20, 54) lineBreakMode:NSLineBreakByTruncatingTail];
//
//        //CGFloat height = [[self.webHeightDic objectForKey:@(indexPath.row)] floatValue];
    
//    return 50 + (size.height > 54 ? 54 : size.height);
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return self.notifications.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    SystemNoticeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SystemNoticeCell"];
    
    [self loadContent:cell indexPath:indexPath];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary *noticeDic = [self.notifications objectAtIndex:indexPath.row];
    NoticeDetailViewController *controller = [[NoticeDetailViewController alloc] init];
    controller.noticeDic = noticeDic;
    [self.navigationController pushViewController:controller animated:YES];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [cell setSeparatorInset:UIEdgeInsetsZero];
        
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        
        [cell setLayoutMargins:UIEdgeInsetsZero];
        
    }
}

@end
